/*
 * @Author: wwssaabb
 * @Date: 2021-11-11 11:42:21
 * @LastEditTime: 2021-12-14 10:10:41
 * @FilePath: \handwritten-code\promise\any.js
 */


//实现promise.any 接收一个可迭代promise对象，当有promise成功时返回这个promise的结果，
//没有一个是成功的promise则rejected并返回一个Error  AggregateError:No Promise in Promise.any was resolved 
//node 没有 any

//与race相似，不同点是race比赛谁的结果更快（不管成功失败），any是第一个成功的结果，如果没有一个成功则为失败

Promise.any = function (arr) {
  return new Promise((resolve, reject) => {
    if (!arr.length) reject(new TypeError('All promises were rejected'))
    let count = 0
    arr.forEach(p => {
      Promise.resolve(p).then(resolve, _ => {
        if (++count === arr.length) reject(new TypeError('All promises were rejected'))
      })
    })
  })
}

const p1 = new Promise((resolve, reject) => setTimeout(() => {
  reject('p1')
  // resolve('p1')
}, 1000))
const p2 = new Promise((resolve, reject) => setTimeout(() => {
  reject('p2')
  // resolve('p2')
}, 2000))
const p3 = new Promise((resolve, reject) => setTimeout(() => {
  reject('p3')
  // resolve('p3')
}, 3000))
const p4 = new Promise((resolve, reject) => setTimeout(() => {
  reject('p4')
  // resolve('p4')
}, 4000))
const p5 = new Promise((resolve, reject) => setTimeout(() => {
  reject('p5')
  // resolve('p5')
}, 5000))

let p = [p1, p2, p3, p4, p5] //, 4, 8, false, null];

Promise.any(p).then(res => console.log(res))
  .catch(err => console.log(err))



// const any = function (arr) {
//   let count = 0
//   return new Promise((resolve, reject) => {
//     arr.forEach(p => Promise.resolve(p).then(resolve, _ => {
//       if (++count === arr.length) reject(new AggregateError('All promise ware rejected'))
//     }))
//   })
// }